// pages/goods_list/index.js
import { axios } from "../../request";
import regeneratorRuntime from "../../libs/runtime";
let PageId;
let Pagenum = 1;
let Pagesize = 6;
let Total = 6
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: []
  },
  async getGoodsList(isPush) {
    // console.log('id: ', id);
    const data = {};
    data.cid = PageId;
    // console.log('PageId: ', PageId);
    // console.log('Pagenum: ', Pagenum);
    data.pagenum = Pagenum;
    data.pagesize = Pagesize;
    const res = await axios({ url: "/goods/search", data });
    let { goods, pagenum, total } = res.message;
    // console.log('pagenum: ', pagenum);
    Total = total;
    // 判断是否后添加 
    if (isPush) {
      goods = [...this.data.goodsList,...goods]
    }
    this.setData({ goodsList: goods });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    PageId = options.id;
    Pagenum = 1;
    Pagesize = 6;
    Total = 6
    // console.log('PageId: ', PageId);
    this.getGoodsList();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getGoodsList();
    // 停止当前页面下拉刷新
    // https://developers.weixin.qq.com/miniprogram/dev/api/ui/pull-down-refresh/wx.stopPullDownRefresh.html
    wx.stopPullDownRefresh();
    // 提示框
    // https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
    wx.showToast({
      title: "数据已跟新",
      icon: "success",
      duration: 2000
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 开始加载
    wx.showLoading({
      title:'正在为您加载中'
    })
    // 向上取整
    const PageSum = Math.ceil(Total / Pagesize) 
    // console.log('PageSum: ', PageSum);
    if (PageSum >= Pagenum) {
      Pagenum++
      // console.log('Pagenum: ', Pagenum);
      this.getGoodsList(true);
    }else {
      // console.log('已经没有数据了');
      wx.showToast({
        title:"已经没有数据了",
      })

    }
    // 关闭加载
    wx.hideLoading()
  },
  // 接受子组件传值
  emitGoodsId(e) {
    console.log('e.detail.id: ', e.detail.id);
    wx.navigateTo({
      url: '/pages/goods_detail/index?id='+e.detail.id,
    });
      
  }
});
